var config = require('./config.js');

var constants = require('./constants.js');

var storage = require('./storage.js');

var platformEnv = require('./platformEnv.js');

//当前平台
let provider = "toutiao";

let code = null;

function request(params, isGetTonken) {

	var isToken = false;
	if (params.url.indexOf("/p/") >= 0 || params.url.indexOf("/u/") >= 0) {
		isToken = true;
		if (!storage.get(constants.TOKEN_DATE)) {
			uni.removeStorageSync(constants.GUO_USER_KEY);
			uni.removeStorageSync(constants.USER_TOKEN_KEY);
			uni.removeStorageSync(constants.GUO_IS_LOGIN);
			uni.removeStorageSync(constants.BIND_USER);
			uni.removeStorageSync(constants.APP_USER_INFO);
			storage.remove(constants.TOKEN_DATE);
			uni.showToast({
				title: '登录信息已过期',
				icon: 'none',
				success(res) {
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/ucenter/ucenter'
						})
					}, 1000);
				}
			})
		}
	}

	uni.request({
		url: params.baseUrl ? config.baseUrl + params.url : config.domain + params.url,
		//接口请求地址
		data: params.data,
		header: {
			//systemType: params.miniApp != '' ? params.miniApp : undefined,
			systemType: platformEnv.SystemType,
			//'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
			Authorization: isToken ? uni.getStorageSync(constants.USER_TOKEN_KEY) : null,
			//Authorization:  uni.getStorageSync(constants.USER_TOKEN_KEY)
			// Authorization: "bearer5fa23a3c-9209-4364-bbcb-637581f4be0e"
		},
		method: params.method == undefined ? 'POST' : params.method,
		dataType: 'json',
		responseType: params.responseType == undefined ? 'text' : params.responseType,
		success: function(res) {
			if (res.statusCode == 200) {
				if (res.data.code == 401) {
					uni.removeStorageSync(constants.GUO_USER_KEY);
					uni.removeStorageSync(constants.USER_TOKEN_KEY);
					uni.removeStorageSync(constants.GUO_IS_LOGIN);
					uni.removeStorageSync(constants.BIND_USER);
					uni.removeStorageSync(constants.APP_USER_INFO);
					storage.remove(constants.TOKEN_DATE);
					uni.showToast({
						title: '登录信息已过期',
						icon: 'none',
						success(res) {
							setTimeout(function() {
								uni.switchTab({
									url: '/pages/ucenter/ucenter'
								})
							}, 1000);
						}
					})
				} else {
					//如果有定义了params.callBack，则调用 params.callBack(res.data)
					if (params.callBack) {
						params.callBack(res.data);
					}
				}

			} else {
				if (res.statusCode == 500) {
					uni.showToast({
						title: '服务器异常',
						icon: 'none'
					});
					uni.hideLoading()
				} else {
					if (res.statusCode == 401) {
						uni.removeStorageSync(constants.GUO_USER_KEY);
						uni.removeStorageSync(constants.USER_TOKEN_KEY);
						uni.removeStorageSync(constants.GUO_IS_LOGIN);
						uni.removeStorageSync(constants.BIND_USER);
						uni.removeStorageSync(constants.APP_USER_INFO);
						storage.remove(constants.TOKEN_DATE);
						uni.showToast({
							title: '登录信息已过期',
							icon: 'none',
							success(res) {
								setTimeout(function() {
									uni.switchTab({
										url: '/pages/ucenter/ucenter'
									})
								}, 1000);
							}
						})
						if (params.errCallBack) {
							params.errCallBack(res);
						}
					} else {
						if (res.statusCode == 400) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						} else {
							//如果有定义了params.errCallBack，则调用 params.errCallBack(res.data)
							if (params.errCallBack) {
								params.errCallBack(res);
							}
						}
					}
				}
			}
		},
		fail: function(err) {
			uni.showToast({
				title: '服务器出了点小差',
				icon: 'none'
			});
			uni.hideLoading()

		}
	});
}

function customRequest(params) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: params.url,
			method: params.method || 'GET',
			data: params.data || {},
			header: {
				//'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
				Authorization: params.login ? undefined : uni.getStorageSync(constants.USER_TOKEN_KEY)
			},
			method: params.method == undefined ? 'POST' : params.method,
			dataType: 'json',
			responseType: params.responseType == undefined ? 'text' : params.responseType,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}



function getUserProfile(fn, that) {
	uni.getUserProfile({
		desc: "获取你的昵称、头像、地区及性别",
		success: function(res) {
			uni.setStorageSync(constants.APP_USER_INFO, res.userInfo);
			uni.setStorageSync(constants.IS_SUCCESS_KEY, true);
			console.log(res);
			loginApp(fn);
		},
		fail: function(err) {
			//快手平台时打开授权
			if (platformEnv.SystemType == 5) {
				uni.openSetting({
					success: function(res) {
						uni.authorize({
							scope: 'scope.userInfo',
							success(settingdata) {},
							fail(error) {}
						});
					},
					fail: (openErr) => {},
				});
			}

		},
		complete: function() {
			that.loginReq = false;
		}
	})
}


/**
 * 登录获取小程序信息
 */
function loginApp(fn) {
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			provider = res.provider;
			uni.login({
				provider: provider,
				success: function(loginRes) {
					code = loginRes.code;
					//getUserInfo(fn);
					loginMini(fn);
				}
			});
		}
	})
}


/**
 * 登录成功后执行
 * @param {Object} result  登录成功返回的数据
 * @param {Object} fn        登录成功后的回调
 */
function loginSuccess(result, fn) {
	// 保存登陆信息
	uni.setStorageSync(constants.GUO_USER_KEY, result)
	// 保存成功登录标识,token过期判断
	uni.setStorageSync(constants.GUO_IS_LOGIN, true)

	if (!result.enabled) {
		uni.showModal({
			showCancel: false,
			title: "提示",
			content: "账号不可用",
			cancelText: "取消",
			confirmText: "确定"
		})
		uni.setStorageSync(constants.USER_TOKEN_KEY, '');
	} else {
		uni.setStorageSync(constants.USER_TOKEN_KEY, 'bearer' + result.access_token); //把token存入缓存，请求接口数据时要用
		storage.put(constants.TOKEN_DATE, result.access_token, constants.EXP_TIME);
	}
	if (result.userId) {
		uni.setStorageSync(constants.BIND_USER, true);
	} else {
		uni.setStorageSync(constants.BIND_USER, false);
	}
	//设置用户信息
	setUserInfo();

	if (fn) {
		fn()
	}

};

/**
 * @param {Object} code 登录小程序
 */
function loginMini(fn) {

	var params = {
		baseUrl: true,
		miniApp: platformEnv.SystemType,
		url: '/login',
		method: 'POST',
		dataType: 'json',
		data: {
			principal: code
		},
		callBack: res => {
			console.log(res);
			loginSuccess(res, fn);
		}
	};
	request(params);
}

function setUserInfo(userInfo) {
	var params = {
		url: '/u/appConnect/setUserInfo',
		method: 'POST',
		dataType: 'json',
		data: JSON.stringify(uni.getStorageSync(constants.APP_USER_INFO)),
		callBack: function(res) {}
	};
	request(params);
}

module.exports = {
	request,
	customRequest,
	loginSuccess,
	loginApp,
	loginMini,
	setUserInfo,
	getUserProfile
};
